use std::collections::HashMap;

use axum::{ Json,  extract::Multipart};
use snowflaked::Generator;
use serde_json::{ json, Value };
use tokio;
use crate::{code, file, utils::host::upload_host };
// 上传到文件夹 varchar 27 位
pub async fn upload(mut multipart: Multipart, mul:bool) -> Result<Json<Value>, Json<Value>>{
    let folder = "upload/temp";
    file::create::create_dir_all_rel(&folder).await?;
    
    let mut g = Generator::new( 0 );        // 雪花唯一值
    // let mut url_arr: Vec<String> = Vec::new();
    let mut err = String::new();

    let mut up_arr:Vec<HashMap<&str,String>> = Vec::new();
    let mut up_obj:HashMap<&str,String> = HashMap::new();

    while let Some(file) = multipart.next_field().await.unwrap_or_default() {
        let mut result:HashMap<&str,String> = HashMap::new();

        let file_name = file.file_name();          // 文件名
        
        if file_name.is_none() {
            err = String::from("上传文件不存在");
            break;
        }
        
        let file_name = file_name.unwrap();
        let file_name_ = file_name.to_owned();

        if mul {
            result.insert("name", file_name.to_owned());
        }else {
            up_obj.insert("name", file_name.to_owned());
        }
        
        let rename = g.generate::<u64>().to_string();    // 唯一值
        let save_file_name = get_file_name(folder, file_name, &rename);
        let last_file_name = "./".to_string() + &save_file_name;
        // 上传到文件夹
        match file.bytes().await {
            Ok(f) => {
                match tokio::fs::write(&last_file_name, &f).await {
                    Ok(_f) => {
                        // 配置输出
                        let host = upload_host();
                        let url = host + &save_file_name;
                        if mul {
                            // url_arr.push( url.to_owned() );
                            result.insert("url",url);
                        }else{
                            up_obj.insert("url",url);
                        }
                        
                        if mul {
                            up_arr.push(result)
                        }
                    },
                    Err(e) => {
                        err = e.to_string();
                        break;
                    }
                };
            },
            Err(_) => {
                err = format!("上传文件【{}】不存在", &file_name_);
                break;
            }
        }
    }
    if err.is_empty() {
        if mul {
            code::data(json!(up_arr))
        }else{
            code::data(json!(up_obj))
        }
    }else{
        code::sys(err)
    }
}

// 获取文件名，如：xxxxx.png，转换成如：/upload/12323.png
pub fn get_file_name(folder:&str, file_name:&str, rename:&str) -> String{
    let path = std::path::Path::new(file_name);
    let suffix = path.extension().map(|ext| ext.to_str().unwrap()).unwrap_or_default();    // 获取后缀名
    format!("{}/{}.{}", folder, rename, suffix)
}